$(function () {
  var App = {

    //TODO: Find a better way to set these from config.php
    baseUrl : '/zwop/',
    maxCharacters: 320,

    init: function () {
      this.setElements();
      this.bindEvents();
    },

    // Cache all the jQuery selectors for easy reference.
    setElements: function () {
      //config operation
      this.$configOpenButton = $('#btnConfigOpen');
      this.$configAddButton = $('#btnConfigAdd');
      this.$configDeleteButton = $('#btnConfigDelete');
      this.$configSubmitButton = $('#btnConfigSubmit');
      
    },

    // Bind document events and assign event handlers.
    bindEvents: function () {
      this.$configOpenButton.on('click',this.openConfigFile);
    },


    /* *************************************
     *             Event Handlers
     * ************************************* */

    
    /**
     * Click handler for the Open button in config.php. 
     * It opens specified config file of system and display 
     * on textarea `configContent` and submits it to config_open
     * function in the Config controller
     *
     * @param e event
     */
    openConfigFile : function (e) {
        var modName = $.trim(document.getElementById("configModName").textContent);

        var selectedData = {
            modname    : modName,
            configname : $('#configSelect').val()
        };
        var postUrl = App.baseUrl + '/config/config_open';
        $.ajax({
            type: 'POST',
            url: postUrl,
            dataType: 'text',
            data: selectedData,
            success: App.configOpenDone,
            error: App.alertError
        })
    },

    /* *************************************
     *             AJAX Callbacks
     * ************************************* */

    
    /**
     * A selected config file has been opened, and the server has responed (or errored)
     * @param response
     */
    configOpenDone : function(response) {
                         if (response){
                             $('#configContent').val(response);
                         }
                     },
    /**
     * Util method for blasting an error message on the screen.
     * @param error
     */
    alertError : function( error ) {
       var args = arguments;
       var msg = error.responseText;
    }

  };

  App.init();

});
